#pragma once
#include "./InetworkModule/InetworkModule.hpp"
#include "./UserModule/UserModule.hpp"

class Server
{
public:
    Server(uint16_t port) 
        : mysql_helper(std::make_shared<MySQLHelper>("127.0.0.1", "zchat", "123456", "zchat", 3306))
        , inet_module(std::make_shared<InetworkModule>(port))
        , user_module(std::make_shared<UserModule>(mysql_helper))
    {
        inet_module->onConnect(std::bind(&Server::onConnection, this, std::placeholders::_1));
        inet_module->onDisConnect(std::bind(&Server::onDisConnection, this, std::placeholders::_1));
        inet_module->onUnknownCallback(std::bind(&Server::onUnknownCallback, this, std::placeholders::_1));

        inet_module->registerCallback<ProtocolLoginReq>(Protocol::Type::LoginReq, std::bind(&Server::Login, this, std::placeholders::_1, std::placeholders::_2));
        
        
        inet_module->registerCallback<ProtocolRegisterReq>(Protocol::Type::RegisterReq, std::bind(&Server::Register, this, std::placeholders::_1, std::placeholders::_2));
    }

    void Login(const TcpConnectPtr& conn, const ProtocolLoginReqPtr& req)
    {
        DLOG("登录请求到来: 用户账号：%s, 密码：%s", req->getUserid().c_str(), req->getPassword().c_str());
        
        Code code = user_module->userLoging(req->getUserid(), req->getPassword());
        ProtocolCommonRespPtr resp = std::dynamic_pointer_cast<ProtocolCommonResp>(ProtocolFactory::createProtocol(Protocol::Type::CommonResp));
        resp->setCode(code);
        DLOG("登陆请求结果：%d", code);
        inet_module->Send(conn, resp);
    }

    void Register(const TcpConnectPtr& conn, const ProtocolRegisterReqPtr& req)
    {
        // user_module->userRegister(req->getUsername(), req->getUserid(), req->getPassword(), Uuid::uuid(), req->getHead());
        DLOG("注册请求到来: 用户名：%s, 用户账号：%s, 密码：%s, 头像：%s", req->getUsername().c_str(), req->getUserid().c_str(), req->getPassword().c_str(), req->getHead().c_str());
        inet_module->Send(conn, req);
    }



    void Start()
    {
        inet_module->Start();
    }

    void onConnection(TcpConnectPtr conn)
    {
        DLOG("新连接到来");
    }

    void onDisConnection(TcpConnectPtr conn)
    {
        DLOG("断开连接");
    }

    void onUnknownCallback(TcpConnectPtr conn)
    {
        DLOG("未知请求，将断开连接");
    }

    ~Server()
    {

    } 
private:
    // 数据库基础指针
    MySQLHelper::Ptr mysql_helper;

    // 这里放一些处理网络连接以及业务处理的各个模块
    InetworkModule::Ptr inet_module;

    // 用户模块管理
    UserModule::Ptr user_module;
};